package com.corticon.dialogs.dao.hibernate;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.LockMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.corticon.dialogs.dao.GenericDAO;
import com.corticon.dialogs.util.Pager;
import com.corticon.dialogs.util.hibernate.EnhancedExample;

/**
 * Annotation Resource is used to retrieve a component from applicationContext instend of <property>
 * in XML config file.
 *
 * @author Yanglifan
 * @param <T>
 * @param <ID>
 */
public abstract class GenericHibernateDAO<T, ID extends Serializable> implements GenericDAO<T, ID> {

    private Class<T> entityClass;
    @Resource
    private SessionFactory sessionFactory;
    private String defaultOrder = "id";
    private boolean defaultOrderAsc = true;

    @SuppressWarnings("unchecked")
    public GenericHibernateDAO() {
        this.entityClass =
            (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).
            getActualTypeArguments()[0];
    }

    @Override
    public T load(ID id) {
        return (T) getSession().load(entityClass, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T findById(ID id, boolean lock) {
        T entity;
        if (lock) {
            entity = (T) getSession().get(entityClass, id);
            getSession().lock(entity, LockMode.WRITE);
        } else {
            entity = (T) getSession().get(entityClass, id);
        }
        return entity;
    }

    @Override
    public T findById(ID id) {
        return findById(id, false);
    }

    // add by heweiya
    protected List<T> findBySQLQuery(String sql) {
        return (List<T>) getSession().createSQLQuery(sql).list();
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<T> findAll() {
        return getBaseCriteria().list();
    }

    @Override
    public List<T> findByExample(T example, String... excludeProperty) {
        return getExampleCriteria(example, excludeProperty).list();
    }

    @Override
    public Serializable save(T entity) {
        Serializable id = getSession().save(entity);
        return id;
    }

    @Override
    public void update(T entity) {
        getSession().update(entity);
    }

    @Override
    public void saveOrUpdate(T entity) {
        getSession().saveOrUpdate(entity);
    }

    @SuppressWarnings("unchecked")
    @Override
    public T merge(T entity) {
        return (T) getSession().merge(entity);
    }

    @Override
    public void delete(T entity) {
        getSession().delete(entity);
    }

    /**
     * 
     * @return
     */
    @Override
    public long getCountAll() {
        return getCount(getBaseCriteria());
    }

    @Override
    public long getCountByExample(T example, String... excludeProperty) {
        return getCount(getExampleCriteria(example, excludeProperty));
    }

    @Override
    public long getCountByUnionExamples(T[] examples, String... excludeProperty) {
        return getCount(getUnionExamplesCriteria(examples, excludeProperty));
    }

    @Override
    public List<T> getPageOfDataAll(Pager pager) {
        return getPageOfData(getBaseCriteria(), pager);
    }

    @Override
    public List<T> getPageOfDataByExample(T example, Pager pager, String... excludeProperty) {
        return getPageOfData(getExampleCriteria(example, excludeProperty), pager);
    }

    @Override
    public List<T> getPageOfDataByUnionExamples(T[] examples, Pager pager, String... excludeProperty) {
        return getPageOfData(getUnionExamplesCriteria(examples, excludeProperty), pager);
    }

    // ********** Helper Methods ********** //
    public Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    /**
     * Get the Criteria according to the Entity Class.
     *
     * @return Criteria
     */
    protected Criteria getBaseCriteria() {
        return getSession().createCriteria(getEntityClass());
    }

    /**
     * Get the number of the result of the Criteria.
     *
     * @param criteria
     * @return
     */
    protected long getCount(Criteria criteria) {
        criteria.setProjection(Projections.rowCount());

        Long result = Long.valueOf(criteria.uniqueResult().toString());
        if (result == null) {
            return 0;
        } else {
            return result;
        }
    }

    /**
     * Get the {@link Example} {@link Criteria} according to the entity class.
     *
     * @param T example
     * @return The responding
     */
    protected Criteria getExampleCriteria(T example, String... excludeProperty) {
        EnhancedExample hibExample = EnhancedExample.create(example);

        for (String exclude : excludeProperty) {
            hibExample.excludeProperty(exclude);
        }

        return getBaseCriteria().add(hibExample);
    }

    /**
     * Get the {@link Criteria} by multi {@link Example} union.
     *
     * @param examples
     * @param excludeProperty
     * @return
     */
    protected Criteria getUnionExamplesCriteria(T[] examples, String... excludeProperty) {

        Criteria criteria = getBaseCriteria();

        List<Criterion> enhancedExamples = new ArrayList<Criterion>();

        for (T example : examples) {

            // Create an Example.
            EnhancedExample hibExample = EnhancedExample.create(example);

            // Add exclude properties.
            for (String exclude : excludeProperty) {
                hibExample.excludeProperty(exclude);
            }

            enhancedExamples.add(hibExample);
        }

        for (int i = 0; i + 1 < enhancedExamples.size(); i++) {

            enhancedExamples.set(i + 1, Restrictions.or(enhancedExamples.get(i), enhancedExamples.
                get(i + 1)));

            if (i + 2 == enhancedExamples.size()) {
                criteria.add(enhancedExamples.get(i + 1));
            }
        }

        return criteria;
    }

    @SuppressWarnings("unchecked")
    protected List<T> getPageOfData(Criteria criteria, Pager pager) {
        return addPager(criteria, pager).list();
    }

    protected Criteria addPager(Criteria criteria, Pager pager) {
        String column = pager.getSortColumn();
        if (column == null) {
            addDefaultOrder(criteria);
        } else {
            boolean sortAsc = pager.isSortAsc();
            addOrder(criteria, column, sortAsc);
        }

        criteria.setFirstResult(pager.getFirstRecord());
        criteria.setMaxResults(pager.getPageSize());

        return criteria;
    }

    protected Criteria addDefaultOrder(Criteria criteria) {
        return addOrder(criteria, getDefaultOrder(), isDefaultOrderAsc());
    }

    protected Criteria addOrder(Criteria criteria, String column, boolean sortAsc) {
        if (column.indexOf("\\.") == -1) {
            if (sortAsc) {
                criteria.addOrder(Order.asc(column));
            } else {
                criteria.addOrder(Order.desc(column));
            }
        } else {
            if (sortAsc) {
                criteria.createCriteria(column.split("\\.")[0]).addOrder(Order.asc(column.split("\\.")[1]));
            } else {
                criteria.createCriteria(column.split("\\.")[0]).addOrder(Order.desc(column.split("\\.")[1]));
            }
        }

        return criteria;
    }
    // ********** Getters and Setters ********** //

    public Class<T> getEntityClass() {
        return entityClass;
    }

    public void setEntityClass(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public String getDefaultOrder() {
        return defaultOrder;
    }

    public void setDefaultOrder(String defaultOrder) {
        this.defaultOrder = defaultOrder;
    }

    public boolean isDefaultOrderAsc() {
        return defaultOrderAsc;
    }

    public void setDefaultOrderAsc(boolean defaultOrderAsc) {
        this.defaultOrderAsc = defaultOrderAsc;
    }
}
